package com.xzd.controller.login;

import java.util.HashMap;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import lombok.extern.slf4j.Slf4j;

@Controller
@Slf4j
public class LoginController {

	@ResponseBody
	@RequestMapping(value="/login_check")
	public Map<String,Object> initVm(
			@RequestParam(required = false, value = "loginName", defaultValue = "") String loginName,
			@RequestParam(required = false, value = "password", defaultValue = "") String password) throws Exception{
		//model.addAttribute("test", "xzd");
		Map<String,Object> map = new HashMap<String,Object>();
		
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(loginName, password.toCharArray(),true);
		
		try {
			System.out.println(subject);
			if(!subject.isAuthenticated()){
				subject.login(token);
			}
			map.put("result","success");
		} catch (UnknownAccountException e) {
			log.error("账号不存在...");
			map.put("result","userunknown");
		}catch (DisabledAccountException e) {
			log.error("账号被禁用...");
			map.put("result","disabled");
		}catch (AuthenticationException e) {
			log.error("用户名或者密码错误...");
			map.put("result","usererror");
		}
		
		return map;
	}
	
	@RequestMapping(value="/index")
	public String init1(Model model) throws Exception{
		model.addAttribute("test", 112);
		
		Subject currentUser = SecurityUtils.getSubject();  
		Session session = currentUser.getSession();
		
		return "main/testvm";
	}
	
	@RequestMapping(value="/loginIndex")
	public String login(Model model) throws Exception{
		System.out.println("2:"+Thread.currentThread().getId());
		return "main/login";
	}
	
	@RequestMapping(value="/loginOut")
	public String login() throws Exception{
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return "main/login";
	}
	
	
}
